/**
 * 公共功能函数
 */

// 显示商品详情
function showProductDetail(product) {
  // 这里可以替换为实际的页面跳转或弹窗
  alert(`即将跳转到 ${product.name} 详情页\nID: ${product.id}`);
  // window.location.href = `product.html?id=${product.id}`;
}

// 防止快速点击
function preventFastClick(selector, callback) {
  let lastClickTime = 0;
  const elements = document.querySelectorAll(selector);
  
  elements.forEach(el => {
    el.addEventListener('click', (e) => {
      const now = Date.now();
      if (now - lastClickTime < 1000) return;
      lastClickTime = now;
      callback.call(el, e);
    });
  });
}

// 初始化公共功能
document.addEventListener('DOMContentLoaded', () => {
  // 应用防快速点击
  preventFastClick('.product-card', function() {
    const productId = this.dataset.id;
    // 这里需要根据实际情况获取商品数据
    showProductDetail({id: productId});
  });
  
  // 其他公共初始化代码...
});

/**
 * 封装简单的AJAX请求
 */
function request(url, method = 'GET', data = null) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          resolve(JSON.parse(xhr.responseText));
        } catch (e) {
          resolve(xhr.responseText);
        }
      } else {
        reject(new Error(xhr.statusText));
      }
    };
    
    xhr.onerror = () => reject(new Error('Network Error'));
    xhr.send(data ? JSON.stringify(data) : null);
  });
}

/**
 * 获取URL参数
 */
function getQueryParam(name) {
  const params = new URLSearchParams(window.location.search);
  return params.get(name);
}

/**
 * 设置本地存储
 */
function setStorage(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch (e) {
    console.error('LocalStorage set error:', e);
    return false;
  }
}

/**
 * 获取本地存储
 */
function getStorage(key) {
  try {
    const value = localStorage.getItem(key);
    return value ? JSON.parse(value) : null;
  } catch (e) {
    console.error('LocalStorage get error:', e);
    return null;
  }
}